
#region Imported Namespaces
using System;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
#endregion

namespace PHSRAG.NativeInterface
{
	public class MessageCatalog
	{
		#region Interop
		[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
		private unsafe static extern int FormatMessage(int flags, ref IntPtr source, 
			int messageId, int languageId, ref string buffer, int size, IntPtr* arguments);
		#endregion

		#region Public Methods
		/// <summary>
		/// This method retrieve the textual description (if any) of a Win32 error code from the system error
		/// catalog.
		/// </summary>
		/// <param name="errorCode">Win32 error code for which the description is desired</param>
		/// <returns>Textual description of the error code</returns>
		public unsafe static string GetErrorMessage(int errorCode)
		{
			const int FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x00000100;
			const int FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200;
			const int FORMAT_MESSAGE_FROM_SYSTEM  = 0x00001000;
			const int flags = FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;

			int messageSize = 255;
			string messageBuffer = String.Empty;

			IntPtr source = IntPtr.Zero;
			IntPtr args = IntPtr.Zero;
        
			int result = FormatMessage(flags, ref source, errorCode, 0, ref messageBuffer, messageSize, &args);
			if (result == 0)
				messageBuffer = string.Format("Win32 error code: {0}", errorCode);

			return Regex.Replace(messageBuffer, @"[\r\n]", " ").Trim();
		}
		#endregion
	}
}

// --- EOF ---
